#include<jni.h>
#include<android/bitmap.h>
#include<stdio.h>
#include<stdlib.h>
int seedr,seedg,seedb,seeda;
int deviation;
int iw,ih;
JNIEnv* genv;
jobject imageMask=NULL;
int pixcmp(unsigned int px){//this method is compare pixel to seed;
	int a=(px&0xff000000)>>24;
	int r=(px&0xff0000)>>16;
	int g=(px&0xff00)>>8;
	int b=px&0xff;
	if(a<=seeda+deviation&&a>=seeda-deviation){
		if(r<=seedr+deviation&&r>=seedr-deviation){
			if(g<=seedg+deviation&&g>=seedg-deviation){
				if(b<=seedb+deviation&&b>=seedb-deviation){
					return true;
				}
			}
		}
	}
	return 0;
}
JNIEXPORT jint  JNICALL Java_com_ima_CanvasView_growNear(JNIEnv *env,jobject thiz,jobject bm,jbyteArray selected,jint devia,jint x,jint y){
	JNIEnv envv=*env;	
	genv=env;
	deviation=devia;
	AndroidBitmapInfo* abi=malloc(sizeof(AndroidBitmapInfo));
	if(AndroidBitmap_getInfo(env,bm,abi)){
		iw=abi->width;
		ih=abi->height;
		int len=iw*ih;
		int *xlocs=(int*)malloc(4*len);
		int *ylocs=(int*)malloc(4*len);
		int top=0;
		char *growed=(char*)calloc(1,len);
		xlocs[top]=x;
		ylocs[top]=y;
		jfieldID f1=envv->GetFieldID(env,thiz,"imageMask","Landroid/graphics/Bitmap;");
		envv->GetObjectField(thiz,f1,imageMask);
		unsigned int *data1;
		unsigned int *data2;
		if(AndroidBitmap_lockPixels(env,bm,(void**)&data1)){
			if(AndroidBitmap_lockPixels(env,imageMask,(void**)&data2)){
				unsigned int px=data1[iw*y+x];
				seeda=(px&0xff000000)>>24;
				seedr=(px&0xff0000)>>16;
				seedg=(px&0xff00)>>8;
				seedb=px&0xff;
				jbyte* channel;
				envv->GetByteArrayElements(env,channel,0);
				int filled=1;
				do{
					x=xlocs[top];
					y=ylocs[top];
					px=data1[iw*y+x];
					growed[iw*y+x]=1;
					top--;
					if(pixcmp(px)){
						channel[x+iw*y]=0xff;
						filled++;
					}
					break;
				}while(top>=0);
				free(xlocs);
				free(ylocs);
				free(growed);
				AndroidBitmap_unlockPixels(env,bm);
				return filled;
			}else{
				return -3;
			}
		}else{
			return -2;
		}
	}else{
		return -1;
	}
	return 0;

}
int main(){
	printf("This library used by FloodFill algorithm for android bitmap\n");
}
